import React, { Component } from 'react'
import store from './store/index'
import { trim } from './utils/tool'
import axios from 'axios'
import {
  getInputChangeAction,
  getAddItemAction,
  getDeleteItemAction,
  initListAction
} from './store/actionCreators'
import TodoListUI from './TodoListUI'

export default class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState()
    this.handleChangeInput = this.handleChangeInput.bind(this)
    this.handleStoreChange = this.handleStoreChange.bind(this)
    this.handleBtnClick = this.handleBtnClick.bind(this)
    this.handleItemDelete = this.handleItemDelete.bind(this)
    // 监听store变化，修改组件 state
    store.subscribe(this.handleStoreChange)
  }

  componentDidMount() {
    axios
      .get('/api/list.json')
      .then(res => {
        console.log('TCL: TodoList -> componentDidMount -> res', res)
        const action = initListAction(res.data)
        store.dispatch(action)
      })
      .catch(err => console.error(err))
  }

  render() {
    let { inputValue, list } = this.state
    return (
      <TodoListUI
        inputValue={inputValue}
        list={list}
        handleChangeInput={this.handleChangeInput}
        handleKeyPress={this.handleKeyPress}
        handleBtnClick={this.handleBtnClick}
        handleItemDelete={this.handleItemDelete}
      />
    )
  }

  handleChangeInput(e) {
    const action = getInputChangeAction(e.target.value)
    // 通知 store(reducer) 更新数据
    store.dispatch(action)
  }
  handleKeyPress = e => {
    if (e.key === 'Enter') {
      // this.handleChangeInput(e)
      this.handleBtnClick()
    }
  }
  handleStoreChange() {
    // 从 store 读取数据 更新 组件 state
    this.setState(store.getState())
  }
  handleBtnClick() {
    if (!trim(this.state.inputValue)) {
      return
    }
    const action = getAddItemAction()
    store.dispatch(action)
  }
  handleItemDelete(index) {
    const action = getDeleteItemAction(index)
    store.dispatch(action)
  }
}
